package com.sunfield.talk;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import im.fir.sdk.FIR;
import im.fir.sdk.VersionCheckCallback;

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener, MyAdapter.OnItemClickListener {

    RecyclerView rv_list;
    MyAdapter adapter;

    AudioManager audioManager;
    TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv_list = (RecyclerView) findViewById(R.id.rv_list);
        adapter = new MyAdapter();
        rv_list.setAdapter(adapter);
        rv_list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter.setOnItemClickListener(this);

        initData();

//        checkVersion();

        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        tts = new TextToSpeech(this, this);
    }

    private void initData() {
        String[] voices = getResources().getStringArray(R.array.voice_data);
        List<VoiceInfo> dataList = new ArrayList<>();
        for(String str : voices){
            String[] array = str.split(";");
            dataList.add(new VoiceInfo(array[0], array[1]));
        }
        adapter.setDataList(dataList);
    }

    private void checkVersion(){
        FIR.checkForUpdateInFIR("404544277944c2ce135fc7e2d74b7a4d" , new VersionCheckCallback() {
            @Override
            public void onSuccess(String versionJson) {
                Log.i("fir","check from fir.im success! " + "\n" + versionJson);
                try {
                    JSONObject jsonObj = new JSONObject(new JSONTokener(versionJson));
                    String versionCode = jsonObj.optString("version");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(Exception exception) {
                Log.i("fir", "check fir.im fail! " + "\n" + exception.getMessage());
            }

            @Override
            public void onStart() {
                Toast.makeText(getApplicationContext(), "正在获取", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                Toast.makeText(getApplicationContext(), "获取完成", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onInit(int status) {
        Log.i("tts", "status = " + String.valueOf(status));
        if (status == TextToSpeech.SUCCESS) {
            int result = this.tts.setLanguage(Locale.CHINA);//设置识别语音为中文
            Log.i("tts", "result = " + String.valueOf(result));
        }
    }

    boolean checkVoice() {
        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (current < max / 5) {
            Toast.makeText(this, "请调大音量", Toast.LENGTH_SHORT).show();
//            return false;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tts.stop();
    }

    @Override
    public void onItemClicked(VoiceInfo data) {
        if("欺诈".equals(data.getName())){
            call();
            return;
        }
        if (checkVoice()) {
            tts.stop();
            HashMap<String, String> params=new HashMap();
            params.put(TextToSpeech.Engine.KEY_PARAM_STREAM,"STREAM_NOTIFICATION");//设置播放类型（音频流类型）
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "hello");
            tts.speak(data.getValue(), TextToSpeech.QUEUE_ADD, params);//将这个发音任务添加当前任务之后
            tts.playSilence(100,TextToSpeech.QUEUE_ADD,params);//间隔多长时间
        }
    }
    /**
     * 拨打电话权限
     */
    protected static final int PERMISSION_CALL = 11;
    private void call() {
        int permissionCall = PermissionChecker.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
        if (permissionCall == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + "18640398241");
            intent.setData(data);
            startActivity(intent);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_CALL);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_CALL) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                call();
            }
        }
    }
}
